package com.reggie.module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.common.ResultResponseVo;
import com.reggie.common.enums.front.OrdersEnum;
import com.reggie.module.entity.po.*;
import com.reggie.module.mapper.*;
import com.reggie.module.service.OrderDetailService;
import com.reggie.module.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.reggie.common.Constant.USER_SESSION;

/**
 * @Author 早睡蛋
 * @Date 2022/10/2 13:54:00
 * @Desc:
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;


    /**
     * 用户下单
     *
     * @param orders
     * @param request
     * @return
     */
    @Override
    @Transactional
    public ResultResponseVo submit(Orders orders, HttpServletRequest request) {
        //获取当前下单用户id
        Long userId = (Long) request.getSession().getAttribute(USER_SESSION);
        //获取当前下单的购物的信息
        QueryWrapper<ShoppingCart> shoppingCartQueryWrapper = new QueryWrapper<>();
        shoppingCartQueryWrapper.eq("user_id", userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(shoppingCartQueryWrapper);
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            return OrdersEnum.FAIL.getResultResponseVo();
        }
        //查询用户数据
        User user = userMapper.selectById(userId);
        //查询地址数据
        AddressBook addressBook = addressBookMapper.selectById(orders.getAddressBookId());
        if (addressBook == null) {
            return OrdersEnum.ADDRESS_NULL.getResultResponseVo();
        }
        //唯一id生成
        long orderId = IdWorker.getId();
        //遍历购物车，计算总金额
        AtomicInteger amount = new AtomicInteger(0);
        List<OrderDetail> orderDetails = shoppingCartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //整理order对象数据
        setOrder(orders, addressBook, user, orderId, userId, amount);
        //完成下单业务，向订单表插入数据，一条
        int insert = orderMapper.insert(orders);
        //向订单明细表插入数据，多条
        boolean saveBatch = orderDetailService.saveBatch(orderDetails);
        //下单完成，清空购物车
        int delete = shoppingCartMapper.delete(shoppingCartQueryWrapper);
        if (insert > 0 && saveBatch && delete > 0) {
            return OrdersEnum.PAY_OK.getResultResponseVo();
        }
        return OrdersEnum.PAY_FAIL.getResultResponseVo();
    }

    public void setOrder(Orders orders, AddressBook addressBook, User user, Long orderId, Long userId, AtomicInteger amount) {
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setNumber(String.valueOf(orderId));
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orders.setUserName(user.getName());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
    }

}
